<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-ok="onConfirm"
    title="修改对账金额"
    :mask-closable="false"
    class="modal-dialog-wrapper"
    unmount-on-close
    width="45vw"
  >
    <page-form :model="form" layout="vertical" style="width: 100%" :rules="rules" ref="formRef">
      <a-row>
        <a-col :span="16">
          <page-form-item label="原对账金额" size="1"> {{ unitVal(accountPrice, '元') }}</page-form-item>
          <page-form-item field="statementAmount" label="修改为" required size="1">
            <i-input-number v-model="form.statementAmount" placeholder="请输入" />
          </page-form-item>
        </a-col>
      </a-row>
    </page-form>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" :loading="okLoading" @click="onConfirm">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { unitVal } from '@/utils'
  import { modifyStatementAmountApi } from '@/api/order/sOrder'

  const form = ref({
    id: '',
    statementAmount: '',
  })
  const accountPrice = ref('')

  const rules = {
    statementAmount: { required: true, message: '请输入' },
  }

  const showModal = ref(false)

  const okLoading = ref(false)

  const open = (price, id) => {
    accountPrice.value = price
    form.value.id = id
    showModal.value = true
  }

  const onClose = () => {
    showModal.value = false
    okLoading.value = false
    form.value = {}
  }

  const emit = defineEmits(['feepageConfirm'])

  const formRef = ref()
  const validateFn = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          okLoading.value = false
          console.log(error)
          reject()
        } else {
          resolve()
        }
      })
    })
  }

  const onConfirm = () => {
    okLoading.value = true
    return new Promise((resolve, reject) => {
      validateFn()
        .then(() => {
          okLoading.value = false
          modifyStatementAmountApi(form.value)
            .then(() => {
              Message.success('修改成功')
              showModal.value = false
              emit('feepageConfirm')
            })
            .catch(() => {
              okLoading.value = false
            })
        })
        .catch(() => {
          reject()
        })
    })
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  :deep(.arco-row) {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  :deep(.arco-row-align-start) {
    padding: 0 !important;
  }
  :deep(.arco-col) {
    padding: 0 10px !important;
  }
</style>
